package com.cr.business.service.impl;

import com.cr.business.domain.TbUserBaseInfo;
import com.cr.business.domain.TbUserEntityInfo;
import com.cr.business.domain.dto.EntityReqDto;
import com.cr.business.domain.vo.*;
import com.cr.business.mapper.TbUserBaseInfoMapper;
import com.cr.business.mapper.TbUserEntityInfoMapper;
import com.cr.business.service.ITbUserEntityInfoService;
import com.cr.business.service.TbRegionService;
import com.cr.common.exception.ServiceException;
import com.cr.common.utils.DateUtils;
import com.cr.common.utils.SecurityUtils;
import com.cr.common.utils.StringUtils;
import com.cr.common.utils.bean.BeanUtils;
import com.cr.common.utils.uuid.IdUtils;
import com.cr.system.service.ISysDictDataService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户主体信息Service业务层处理
 * 
 * @author tang
 * @date 2025-08-19
 */
@Service
public class TbUserEntityInfoServiceImpl implements ITbUserEntityInfoService 
{
    @Resource
    private TbUserEntityInfoMapper tbUserEntityInfoMapper;

    @Resource
    private TbUserBaseInfoMapper tbUserBaseInfoMapper;

    @Resource
    private TbRegionService regionService;

    @Resource
    private ISysDictDataService dictDataService;

    /**
     * 新增用户主体信息
     * 
     * @param tbUserEntityInfo 用户主体信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTbUserEntityInfo(TbUserEntityInfo tbUserEntityInfo)
    {
        validate(tbUserEntityInfo);

        // 当前用户ID
        String appUserId = SecurityUtils.getAppUserId();
        TbUserEntityInfo info = tbUserEntityInfoMapper.selectTbUserEntityInfoByUserId(appUserId);
        if(info != null) {
            throw new ServiceException("当前账号已提交实名信息！");
        }

        String entityId = IdUtils.simpleUUID();
        Date nowDate = DateUtils.getNowDate();

        // 保存实名信息
        tbUserEntityInfo.setEntityId(entityId);
        tbUserEntityInfo.setUserId(appUserId);
        tbUserEntityInfo.setAuthSubmitTime(nowDate);
        int i = tbUserEntityInfoMapper.insertTbUserEntityInfo(tbUserEntityInfo);

        // 修改用户实名认证状态
        int u = updateUserAuthStatus(appUserId, entityId, tbUserEntityInfo.getEntityName());

        return i == 1 && u == 1 ? 1 : 0;
    }

    /**
     * 修改用户主体信息
     * 
     * @param tbUserEntityInfo 用户主体信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTbUserEntityInfo(TbUserEntityInfo tbUserEntityInfo)
    {
        validate(tbUserEntityInfo);

        // 当前用户ID
        String appUserId = SecurityUtils.getAppUserId();
        TbUserEntityInfo info = tbUserEntityInfoMapper.selectTbUserEntityInfoByUserId(appUserId);
        if(info == null) {
            throw new ServiceException("当前账号尚未提交实名信息！");
        }
        String entityId = tbUserEntityInfo.getEntityId();
        if(! info.getEntityId().equals(entityId)) {
            throw new ServiceException("当前账号实名信息与提交信息不一致！");
        }

        // 旧数据改为历史数据
        info.setLatestFlag("1");
        int updateOldDataStatus = tbUserEntityInfoMapper.updateTbUserEntityInfo(info);

        Date nowDate = DateUtils.getNowDate();
        // 保存新的实名信息
        String newEntityId = IdUtils.simpleUUID();
        tbUserEntityInfo.setEntityId(newEntityId);
        tbUserEntityInfo.setUserId(appUserId);
        tbUserEntityInfo.setAuthStatus("2");
        tbUserEntityInfo.setAuthSubmitTime(nowDate);
        int entityUpdate = tbUserEntityInfoMapper.insertTbUserEntityInfo(tbUserEntityInfo);

        // 修改用户实名认证状态
        int userUpdate = updateUserAuthStatus(appUserId, newEntityId, tbUserEntityInfo.getEntityName());

        return updateOldDataStatus == 1 && entityUpdate == 1 && userUpdate == 1 ? 1 : 0;
    }

    /**
     * 验证主体信息
     * @param tbUserEntityInfo 主体信息
     */
    private void validate(TbUserEntityInfo tbUserEntityInfo) {
        // 主体类型如果是企业、合作社、其他
        // 则需要证件类型、社会信用代码必填，法人信息、营业执照必填
        String entityType = tbUserEntityInfo.getEntityType();
        if ("101".equals(entityType) || "102".equals(entityType) || "106".equals(entityType)) {
            if (StringUtils.isBlank(tbUserEntityInfo.getCertType())) {
                throw new ServiceException("企业证件类型不能为空！");
            }
            if (StringUtils.isBlank(tbUserEntityInfo.getSocialCreditCode())) {
                throw new ServiceException("社会信用代码不能为空！");
            }

            if(StringUtils.isBlank(tbUserEntityInfo.getLegalPerson())) {
                throw new ServiceException("法人姓名不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getLegalPersonCertType())) {
                throw new ServiceException("法人证件类型不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getLegalPersonCertNo())) {
                throw new ServiceException("法人证件号码不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getLegalPersonPhone())) {
                throw new ServiceException("法人联系号码不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getEntityCert())) {
                throw new ServiceException("主体证照（营业执照）不能为空！");
            }
        } else {
            // 主体类型是家庭农牧场、个体小散户、种养殖大户
            // 则需要联系人信息必填
            if(StringUtils.isBlank(tbUserEntityInfo.getLiaisonMan())) {
                throw new ServiceException("联系人姓名不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getLiaisonManCertType())) {
                throw new ServiceException("联系人证件类型不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getLiaisonManCertNo())) {
                throw new ServiceException("联系人证件号码不能为空！");
            }
            if(StringUtils.isBlank(tbUserEntityInfo.getLiaisonManPhone())) {
                throw new ServiceException("联系人手机号不能为空！");
            }
        }

        // 判断营业期限截止日期
        Date timeLimitEnd = tbUserEntityInfo.getTimeLimitEnd();
        String permanentlyFlag = tbUserEntityInfo.getPermanentlyFlag();
        if(timeLimitEnd == null && ! "1".equals(permanentlyFlag)) {
            throw new ServiceException("营业期限截止日期不能为空！");
        }
    }

    /**
     * 修改用户实名认证状态
     * @param appUserId 用户ID
     * @param entityId 实体ID
     * @param entityName 实体名称
     */
    private int updateUserAuthStatus(String appUserId, String entityId, String entityName) {
        // 修改用户实名认证状态
        TbUserBaseInfo baseInfo = new TbUserBaseInfo();
        baseInfo.setUserId(appUserId);
        baseInfo.setEntityId(entityId);
        baseInfo.setBusinessEntity(entityName);
        baseInfo.setAuthStatus("2");
        return tbUserBaseInfoMapper.updateTbUserBaseInfo(baseInfo);
    }

    /**
     * 查询用户主体信息
     */
    @Override
    public AppAuthData selectTbUserEntityInfo()
    {
        AppAuthData authData = new AppAuthData();
        // 当前用户ID
        String appUserId = SecurityUtils.getAppUserId();
        // 查询实名认证信息
        TbUserEntityInfo info = tbUserEntityInfoMapper.selectTbUserEntityInfoByUserId(appUserId);
        if(info == null || "0".equals(info.getAuthStatus())) {
            authData.setStatus("0");
            return authData;
        }
        // 认证状态（0-未认证，1-已认证，2-审核中，3-审核失败）
        String authStatus = info.getAuthStatus();
        authData.setStatus(authStatus);

        // 已认证返回主体详细信息（包括地区代码转文字、数据字典转文字）
        if("1".equals(authStatus)) {

            // 主体信息
            AppAuthEntityInfo entityInfo = new AppAuthEntityInfo();
            BeanUtils.copyBeanProp(entityInfo, info);

            // 主体类型
            entityInfo.setEntityTypeName(dictDataService.selectDictLabel("business_entity_type", info.getEntityType()));
            // 主体证照类型
            entityInfo.setCertTypeName(dictDataService.selectDictLabel("business_certificate_type", info.getCertType()));
            // 主体属性
            entityInfo.setEntityAttrName(dictDataService.selectDictLabel("business_entity_attribute", info.getEntityAttr()));
            // 主体行业
            entityInfo.setEntityIndustryName(dictDataService.selectDictLabel("business_entity_industry", info.getEntityIndustry()));
            // 商标类型
            entityInfo.setTrademarkName(dictDataService.selectDictLabel("trademark_type", info.getTrademark()));
            // 法人证件类型
            entityInfo.setLegalPersonCertTypeName(dictDataService.selectDictLabel("certificate_type", info.getLegalPersonCertType()));
            // 联系人证件类型
            entityInfo.setLiaisonManCertTypeName(dictDataService.selectDictLabel("certificate_type", info.getLiaisonManCertType()));

            // 省市区镇村
            entityInfo.setProvinceName(regionService.getRegionNameByCode(info.getProvince()));
            entityInfo.setCityName(regionService.getRegionNameByCode(info.getCity()));
            entityInfo.setDistrictName(regionService.getRegionNameByCode(info.getDistrict()));
            entityInfo.setTownName(regionService.getRegionNameByCode(info.getTown()));
            entityInfo.setVillageName(regionService.getRegionNameByCode(info.getVillage()));

            authData.setEntityInfo(entityInfo);
        }

        // 审核失败需要返回主体信息和失败原因
        if("3".equals(authStatus)) {
            // 主体信息
            AppAuthEntityInfo entityInfo = new AppAuthEntityInfo();
            BeanUtils.copyBeanProp(entityInfo, info);
            authData.setEntityInfo(entityInfo);
            // 审核失败原因
            AppAuthFailInfo failInfo = new AppAuthFailInfo();
            BeanUtils.copyBeanProp(failInfo, info);
            authData.setFailInfo(failInfo);
        }

        return authData;
    }

    @Override
    public List<EntityListData> selectEntityList(EntityReqDto params) {
        return tbUserEntityInfoMapper.selectTbUserEntityInfoList(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEntityInfoByIds(String[] entityIds) {
        // 初始化用户实名认证状态
        int u = tbUserBaseInfoMapper.initUserAuthStatus(entityIds);
        // 删除实名信息
        int i = tbUserEntityInfoMapper.deleteTbUserEntityInfoByEntityIds(entityIds);
        return u > 0 && i > 0 ? 1 : 0;
    }

    @Override
    public List<EntityExportData> selectEntityExportList(EntityReqDto params) {
        List<EntityExportData> list = tbUserEntityInfoMapper.selectTbUserEntityInfoExportList(params);
        if (list != null && !list.isEmpty()) {
            for (EntityExportData entity : list) {
                if(entity == null) {
                    continue ;
                }
                // 主体类型
                entity.setEntityType(dictDataService.selectDictLabel("business_entity_type", entity.getEntityType()));
                // 主体证照类型
                entity.setCertType(dictDataService.selectDictLabel("business_certificate_type", entity.getCertType()));
                // 主体属性
                entity.setEntityAttr(dictDataService.selectDictLabel("business_entity_attribute", entity.getEntityAttr()));
                // 主体行业
                entity.setEntityIndustry(dictDataService.selectDictLabel("business_entity_industry", entity.getEntityIndustry()));
                // 商标类型
                entity.setTrademark(dictDataService.selectDictLabel("trademark_type", entity.getTrademark()));
                // 法人证件类型
                entity.setLegalPersonCertType(dictDataService.selectDictLabel("certificate_type", entity.getLegalPersonCertType()));
                // 联系人证件类型
                entity.setLiaisonManCertType(dictDataService.selectDictLabel("certificate_type", entity.getLiaisonManCertType()));

                // 省市区镇村
                entity.setProvince(regionService.getRegionNameByCode(entity.getProvince()));
                entity.setCity(regionService.getRegionNameByCode(entity.getCity()));
                entity.setDistrict(regionService.getRegionNameByCode(entity.getDistrict()));
                entity.setTown(regionService.getRegionNameByCode(entity.getTown()));
                entity.setVillage(regionService.getRegionNameByCode(entity.getVillage()));

                // 是否长期（0-否，1-是）
                String permanentlyFlag = entity.getPermanentlyFlag();
                if ("1".equals(permanentlyFlag)) {
                    entity.setBusinesstimeLimit(DateUtils.parseDateToStr("yyyy-MM-dd", entity.getTimeLimitStart()) + "至长期");
                } else {
                    entity.setBusinesstimeLimit(DateUtils.parseDateToStr("yyyy-MM-dd", entity.getTimeLimitStart()) + "至" + DateUtils.parseDateToStr("yyyy-MM-dd", entity.getTimeLimitEnd()));
                }
                // 经纬度坐标
                entity.setCoordinates(entity.getLongitude() + "," + entity.getLatitude());
            }
        }
        return list;
    }

    @Override
    public int updateEntityInfoStatus(String entityId, String status) {

        TbUserEntityInfo info = new TbUserEntityInfo();
        info.setEntityId(entityId);
        info.setStatus(status);
        return tbUserEntityInfoMapper.updateTbUserEntityInfo(info);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int authEntityInfo(String entityId, String result, String reasons) {

        TbUserEntityInfo tbUserEntityInfo = tbUserEntityInfoMapper.selectTbUserEntityInfoById(entityId);
        if (tbUserEntityInfo == null) {
            throw new ServiceException("主体信息不存在！");
        }
        Date nowDate = DateUtils.getNowDate();

        // 修改主体信息状态
        TbUserEntityInfo info = new TbUserEntityInfo();
        info.setEntityId(entityId);
        info.setAuthStatus(result);
        info.setAuthFailReason(reasons);
        info.setAuthTime(nowDate);
        int i = tbUserEntityInfoMapper.updateTbUserEntityInfo(info);

        // 修改用户实名认证状态
        TbUserBaseInfo userInfo = new TbUserBaseInfo();
        userInfo.setUserId(tbUserEntityInfo.getUserId());
        userInfo.setAuthStatus(result);
        userInfo.setAuthTime(nowDate);
        int u = tbUserBaseInfoMapper.updateTbUserBaseInfo(userInfo);

        return i>0 && u>0 ? 1 : 0;
    }

    @Override
    public Map<String, Object> appGetEntityInfo() {

        // 当前用户ID
        String appUserId = SecurityUtils.getAppUserId();

        // 查询用户实名状态
        TbUserBaseInfo tbUserBaseInfo = tbUserBaseInfoMapper.selectTbUserBaseInfoByUserId(appUserId);
        if (tbUserBaseInfo == null) {
            throw new ServiceException("用户信息不存在！");
        }
        if(! "1".equals(tbUserBaseInfo.getAuthStatus())) {
            throw new ServiceException("用户未完成实名认证！");
        }

        // 查询实名信息
        TbUserEntityInfo entity = tbUserEntityInfoMapper.selectTbUserEntityInfoByUserId(appUserId);
        if (entity == null) {
            throw new ServiceException("主体信息不存在！");
        }
        // 省市区镇村
        String provinceName = regionService.getRegionNameByCode(entity.getProvince());
        String cityName = regionService.getRegionNameByCode(entity.getCity());
        String districtName = regionService.getRegionNameByCode(entity.getDistrict());
        String townName = regionService.getRegionNameByCode(entity.getTown());
        String villageName = regionService.getRegionNameByCode(entity.getVillage());

        Map<String, Object> info = new HashMap<>();
        info.put("entityName", entity.getEntityName());
        info.put("detailedAddress", provinceName + cityName + districtName + townName + villageName + entity.getAddress());
        info.put("longitude", entity.getLongitude());
        info.put("latitude", entity.getLatitude());
        return info;
    }

    @Override
    public Map<String, Object> appGetEntityInfo(String entityId) {
        TbUserEntityInfo entity = tbUserEntityInfoMapper.selectTbUserEntityInfoById(entityId);
        if (entity != null) {
            // 省市区镇村
            String provinceName = regionService.getRegionNameByCode(entity.getProvince());
            String cityName = regionService.getRegionNameByCode(entity.getCity());
            String districtName = regionService.getRegionNameByCode(entity.getDistrict());
            String townName = regionService.getRegionNameByCode(entity.getTown());
            String villageName = regionService.getRegionNameByCode(entity.getVillage());

            Map<String, Object> info = new HashMap<>();
            info.put("name", entity.getEntityName());
            info.put("address", provinceName + cityName + districtName + townName + villageName + entity.getAddress());
            info.put("phone", entity.getLiaisonManPhone());

            return info;
        }
        return Collections.emptyMap();
    }
}
